#!/usr/bin/perl
#
# castcopy - cast
# Copyright (C) 2007 Nick Bargnesi <nick at den-4.com>
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
use strict;
use warnings;
use CastCopy;

my $filename;
my $cfgfile = '/etc/castcopy.cfg';
my $verbose = 0;
set_caller($0);
&check_args(@ARGV);
set_verbose($verbose);
sysprint("Using configuration file");
sysprint_end($cfgfile);
init($cfgfile);
if (! $verbose) {
    print "$0: started sending $filename\n";
}
send_file($filename);
if (! $verbose) {
    print "$0: send complete\n";
}
uninit;

sub check_args {
    my $arg = shift;
    while ($arg) {
        if ($arg eq "--help" or $arg eq "-H" or $arg eq "-h") {
            &usage_options_and_exit;
        } elsif ($arg eq "--verbose" or $arg eq "-V" or $arg eq "-v") {
            $verbose = 1;
        } elsif ($arg eq "--config" or $arg eq "-C" or $arg eq "-c") {
            $arg = shift;
            $cfgfile = $arg;
            if (! $cfgfile) {
                &usage_and_exit;
            }
        } else {
            if ($filename) {
                print("$0: File already specified ($filename)\n");
                &usage_and_exit;
            } else {
                if ( ! -r $arg) {
                    die("$0: File not readable: $!");
                }
                $filename = $arg;
            }
        }
        $arg = shift;
    }
    if (! $filename) {
        &usage_and_exit;
    }
}

sub usage_options_and_exit {
    print "Usage: $0 [OPTION]... [FILENAME]\n";
    print "Send FILENAME to the multicast channel.\n";
    print "Example: $0 $ENV{'HOME'}/.bashrc\n";
    print "\n";
    print "Options:\n";
    print "  --help, -H\t\tDisplays this help.\n";
    print "  --verbose, -V\t\tVerbose mode.\n";
    print "  --config, -C\t\tConfiguration file, defaults to '/etc/castcopy.cfg'.\n";
    exit;
}

sub usage_and_exit {
    print "Usage: $0 [OPTION]... [FILENAME]\n";
    print "Try \'$0 --help\' for more information.\n";
    exit;
}

